﻿var callbackParam = 'callback';
function ajax(method, url, data, options) {
    var parameters = method === 'GET' ? data : jQuery.stringifyJSON(data);
    var o = {
        url: url,
        data: parameters,
        type: method,
        contentType: 'application/json',
        dataType: 'text json',
        traditional: 'true',
        error: function (response) {
            if (response.status === 400) {
                if (response.responseText == "403") {
                    toastr.error("对不起，你无权访问该页面数据");
                } else {
                    toastr.error(response.responseText);
                }
            }
        }
    };
    if (options) {
        $.extend(o, options);
    }
    return $.ajax(o);
}
var http = {
    /**
     * The name of the callback parameter to inject into jsonp requests by default.
     * @property {string} callbackParam
     * @default callback
     */
    callbackParam: 'callback',
    /**
     * Makes an HTTP GET request.
     * @method get
     * @param {string} url The url to send the get request to.
     * @param {object} [query] An optional key/value object to transform into query string parameters.
     * @return {Promise} A promise of the get response data.
     */
    get: function (url, query) {
        return ajax('GET', url, query);
    },
    /**
     * Makes an JSONP request.
     * @method jsonp
     * @param {string} url The url to send the get request to.
     * @param {object} [query] An optional key/value object to transform into query string parameters.
     * @param {string} [callbackParam] The name of the callback parameter the api expects (overrides the default callbackParam).
     * @return {Promise} A promise of the response data.
     */
    jsonp: function (url, query, callbackParam) {
        if (url.indexOf('=?') == -1) {
            callbackParam = callbackParam || this.callbackParam;

            if (url.indexOf('?') == -1) {
                url += '?';
            } else {
                url += '&';
            }

            url += callbackParam + '=?';
        }

        return $.ajax({
            url: url,
            dataType: 'jsonp',
            data: query
        });
    },
    /**
     * Makes an HTTP POST request.
     * @method post
     * @param {string} url The url to send the post request to.
     * @param {object} data The data to post. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
     * @return {Promise} A promise of the response data.
     */
    post: function (url, data, options) {
        return ajax('POST', url, data, options);
    },
    put: function (url, data, options) {
        return ajax('PUT', url, data, options);
    },
    del: function (url) {
        return ajax('DELETE', url);
    }
};
var special = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' },
	escape = function (chr) { return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4); };
jQuery.stringifyJSON = function (data) {
    // use native if exists
    if (window.JSON && window.JSON.stringify)
        return window.JSON.stringify(data);

    switch (jQuery.type(data)) {
        case 'string':
            return '"' + data.replace(/[\x00-\x1f\\"]/g, escape) + '"';
        case 'array':
            return '[' + jQuery.map(data, jQuery.stringifyJSON) + ']';
        case 'object':
            var string = [];
            jQuery.each(data, function (key, val) {
                var json = jQuery.stringifyJSON(val);
                if (json)
                    string.push(jQuery.stringifyJSON(key) + ':' + json);
            });
            return '{' + string + '}';
        case 'number':
        case 'boolean':
            return '' + data;
        case 'undefined':
        case 'null':
            return 'null';
    }

    return data;
};

$.eval = function (data) {
    if (data && data.length > 0) {
        for (var j = 0; j < data.length; j++) {
            if (data[j].click) {
                if (window.eval) {
                    data[j].click = window.eval(data[j].click);
                } else {
                    data[j].click = window.execScript(data[j].click);
                }
            }
        }
        return data;
    }
    return undefined;
};

$.fileDownload = function (url, data) {
    var param = [];
    for (var i in data) {
        if (data[i]) {
            param.push(i + "=" + data[i]);
        }
    }
    if (param.length) {
        url += "?" + param.join("&");
    }
    if ($('#ifmfiledownload').length <= 0)
    $('body').append("<iframe id=\"ifmfiledownload\" style=\"display:none\"></iframe>");
    $('#ifmfiledownload').attr('src', encodeURI(url));
};